package com.atjava.webspider.database;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public abstract class JDBCManager {
	
	protected Connection connection;
	
	public JDBCManager(Connection con){
		this.connection = con;
	}
	
	public void closeStatement(Statement st){
		try{
			if(st != null)
				st.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public void closeResultSet(ResultSet rs){
		try{
			if(rs != null)
				rs.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	public int update(String sql)throws Exception{
		Statement st = connection.createStatement();
		int n = 0;
		try {
			n = st.executeUpdate(sql);
		} catch (Exception e) {
			throw e;
		} finally{
			closeStatement(st);
		}
		return n;
	}
	
	public List<Object []> query(String sql)throws Exception{
		List<Object []> list = new ArrayList<Object []>();
		ResultSet rs = null;
		Statement st = connection.createStatement();
		try {
			rs = st.executeQuery(sql);
			int col = rs.getMetaData().getColumnCount();
			while(rs.next()){
				Object [] objs = new Object[col];
				for(int i=0;i<objs.length;i++){
					objs[i] = rs.getObject(i+1);
				}
				list.add(objs);
			}
		} catch (Exception e) {
			throw e;
		} finally{
			closeResultSet(rs);
			closeStatement(st);
		}
		return list;
	}
	
	public abstract List<String> getTables() throws Exception;
	
	public abstract List<String> getTableFields(String table) throws Exception;
	
	//public abstract String getPrimaryKey(String table)throws Exception;
	
}
